package com.galen.wxRead.filter;

import com.alibaba.fastjson.JSON;
import com.galen.wxRead.core.pojo.ErrorResult;
import com.galen.wxRead.core.pojo.ResultCode;
import com.galen.wxRead.domain.ReadUser;
import com.galen.wxRead.domain.ReadWx;
import com.galen.wxRead.mapper.ReadUserMapper;
import com.galen.wxRead.redis.RedisCache;
import com.galen.wxRead.redis.RedisKeys;
import com.galen.wxRead.utils.spring.SpringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class SessionFilter implements Filter {

    private RedisCache redisCache = SpringUtils.getBean(RedisCache.class);

    private ReadUserMapper readUserMapper = SpringUtils.getBean(ReadUserMapper.class);

    //不需要登录就可以访问的路径(比如:注册登录等)
    String[] includeUrls = new String[]{"/login","/addOrder","/getOrder","/getOrderList","/addReadWx","/delReadWx","/addOrderList","/getReadWx","/addReadTask","/addReadWxList","/updateReadTask","/delOrder","/setReadWxLimit","/getReadWxLimit"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //解决跨域访问报错
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        //设置过期时间
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        // 支持HTTP 1.1.
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        // 支持HTTP 1.0. response.setHeader("Expires", "0");
        response.setHeader("Pragma", "no-cache");
        // 编码
        response.setCharacterEncoding("UTF-8");
        //检测过滤
        String uri = request.getRequestURI();
        //是否需要过滤
        boolean needFilter = false;
        if (needFilter) {
            // 初始化自定义HttpServletRequestWrapper
            ChangeRequestWrapper changeRequestWrapper = new ChangeRequestWrapper((HttpServletRequest) servletRequest);
            // 获取所有参数集合
            Map<String, String[]> parameterMap = new HashMap<>(changeRequestWrapper.getParameterMap());
            String[] strings = parameterMap.get("session");
            //逻辑代码 判断有没有传入session
            if (strings == null || strings.length == 0) {
                ErrorResult error = ErrorResult.fail(ResultCode.USER_NOTLOGGED_IN.code(), ResultCode.USER_NOTLOGGED_IN.message());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.append(JSON.toJSONString(error));
            } else {
                //判断session
                Object obj = redisCache.getCacheObject(RedisKeys.getSession(strings[0]));
                if (obj == null) {
                    ErrorResult error = ErrorResult.fail(ResultCode.USER_SESSION_TIMEOUT.code(), ResultCode.USER_SESSION_TIMEOUT.message());
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter out = response.getWriter();
                    out.append(JSON.toJSONString(error));
                } else {
                    //添加cdKey参数
                    ReadUser readUser = JSON.parseObject(obj.toString(), ReadUser.class);
                    String[] userArray = new String[1];
                    userArray[0] = readUser.getUser();
                    parameterMap.put("user", userArray);
                    changeRequestWrapper.setParameterMap(parameterMap);
                    filterChain.doFilter(changeRequestWrapper, servletResponse);
                }
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    /**
     * @param uri
     * @Author: xxxxx
     * @Description: 是否需要过滤
     * @Date: 2018-03-12 13:20:54
     */
    public boolean isNeedFilter(String uri) {
        for (String includeUrl : includeUrls) {
            if (includeUrl.equals(uri)) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}